import {
  Button,
  Card,
  Descriptions,
  Input,
  Table,
  Form,
  message,
  Row,
  Col
} from "antd";
import React from "react";
import styles from "./detail.less";
import { connect } from "dva";
import Chart from "../../components/Chart";
import { WordClouds } from "./echarts";
import { routerRedux } from "dva/router";

const dataSource = [
  {
    key: "1",
    name: "胡彦斌",
    type: "ftp",
    address: "西湖区湖底公园1号",
    time: "2020-01-01"
  },
  {
    key: "2",
    name: "胡彦祖",
    type: "ftp",
    address: "西湖区湖底公园1号",
    time: "2020-01-01"
  }
];

const columns = [
  {
    title: "姓名",
    dataIndex: "name",
    key: "name",
    width: "20%",
    align: "center"
  },
  {
    title: "内容",
    dataIndex: "content",
    key: "content",
    width: "50%",
    align: "center"
  },

  {
    title: "创建时间",
    dataIndex: "createTime",
    key: "createTime",
    width: "30%",
    align: "center"
  }
];
@connect(({ global }) => ({ userId: global.userId }))
class StandardDetail extends React.PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      tabs: 0,
      getStandardList: [], //详情
      StandDetailList: [], //列表
      articleList: {},
      id: this.props.match.params.id,
      value: "",
      query: "",//标题
      name: "",
      titleFirst: "",
      unit: "",
      deft: "",
      writeUnit: "",
      author: "",
      column: [],
      hotWordVos: {} //热点标准
    };
  }
  componentDidMount = () => {
    this.getStandardInfo();
    this.getStandDetailInfoListByPage();
  };
  //获取热点标准
  getHotStandard = () => {
    this.props.dispatch({
      type: "global/getAssociationInfo",
      payload: {
        query: this.state.query
      }
    }).then(res => {
      console.log(res);
      let params2 = []
      res && res.data.forEach((item, index) => {
        const color = "#" + (~~(Math.random() * (1 << 24))).toString(16);
        params2[index] = {
          name: index + item.tile,
          value: item.id,
          symbolSize: (Math.random() + 1) * 50,
          draggable: true,
          itemStyle: {
            normal: { shadowBlur: 10, shadowColor: color, color: color }
          }
        };
      });
      this.setState({
        hotWordVos: {
          backgroundColor: "white",
          tooltip: {},
          animationDurationUpdate: function (idx) {
            // 越往后的数据延迟越大
            return idx * 100;
          },
          animationEasingUpdate: "bounceIn",
          color: ["#fff", "#fff", "#fff"],
          series: [
            {
              type: "graph",
              layout: "force",
              force: {
                repulsion: 250,
                edgeLength: 10
              },
              roam: true,
              label: {
                normal: {
                  show: true
                }
              },
              width: 1200,
              height: 500,
              data: params2
            }
          ]
        }
      })
    })
  }
  //点击标准词云
  onHotWordVosClick = (e) => {
    console.log(e);
    this.setState({
      id: e.data.value
    }, () => {
      this.getStandardInfo()
    })
  }
  handleTabsChange = tabs => {
    this.setState({
      tabs
    });
  };
  //标准详情
  getStandardInfo = () => {
    let { id } = this.state;
    this.props
      .dispatch({
        type: "global/getStandardInfo",
        payload: {
          id: id
        }
      })
      .then(res => {
        console.log(res);
        if (res) {
          console.log("getStandardInfo", res.data);
          console.log("tile", res.data.tile.charAt(0));
          this.setState({
            getStandardList: res.data,
            unit: res.data.unit,
            query: res.data.tile,
            deft: res.data.deft,
            titleFirst: res.data.tile.charAt(0),
            writeUnit: res.data.writeUnit,
            author: res.data.author
          }, () => {
            this.getHotStandard()
          });
        } else {
          // console.log("getStandardInfo", res.data);
          // console.log("tile", res.data.tile.charAt(0));
          this.setState({
            getStandardList: res.data,
            unit: res.data.unit,
            query: res.data.tile,
            deft: res.data.deft,
            titleFirst: res.data.tile.charAt(0),
            writeUnit: res.data.writeUnit,
            author: res.data.author
          }, () => {
            this.getHotStandard()
          });
        }
      });
  };
  //标准详细信息列表
  getStandDetailInfoListByPage = () => {
    let { id, name } = this.state;
    this.props
      .dispatch({
        type: "global/getStandDetailInfoListByPage",
        payload: {
          pageSize: 9999999,
          currentPage: 1,
          query: name,
          id: id
        }
      })
      .then(res => {
        // this.getColumns(res.data.rows[0].kv);
        if (res.data.rows.length > 0) {
          let arr = [];
          let Arr = [];
          let OBJ = {};
          res.data.rows[0].kv.map(item => {
            let obj = {
              title: item.name,
              dataIndex: item.name,
              key: item.name,
              align: "center"
            };
            arr.unshift(obj);
          });

          res.data.rows.map(item => {
            item.kv.map(ikv => {
              OBJ = {
                ...OBJ,
                [ikv.name]: ikv.contentValue
              };
            });
            Arr.push(OBJ);
          });

          this.setState(
            {
              column: arr,
              StandDetailList: Arr
            },
            () => {
              console.log(this.state.StandDetailList);
            }
          );
        }
      });
  };
  //设置表头
  getColumns = arr => {
    arr.map(item => { });
  };
  //输入框
  onChange = e => {
    // console.log(e.target.value);
    this.setState({
      value: e.target.value
    });
  };
  //查询
  onSearch = arr => {
    console.log("2222", this.state.value);

    this.setState(
      {
        name: this.state.value
      },
      () => {
        this.getStandDetailInfoListByPage();
      }
    );
    console.log("name1111111", this.state.name);
  };
  //重置
  clear = () => {
    this.setState({
      name: "",
      value: ""
    });
  };
  //下载
  download = fileUrl => {
    // let a = document.createElement("a");
    // let url = `${window.location.origin}/api/jyk/file/download?path=`;
    // let path = `${fileUrl}`;
    // a.href = url + path;
    // a.style.display = "none";
    // document.body.appendChild(a);
    // a.click();
    // document.body.removeChild(a);
    // this.getStandardInfo();
    if (fileUrl !== "") {
      this.props.dispatch({
        type: "global/download",
        payload: {
          path: `${fileUrl}`
        }
      })
        .then(blob => {
          console.log("文件流", blob);
          let filename = fileUrl.split("/")[fileUrl.split("/").length - 1]
          // // let filename = decodeURI(headers["content-disposition"].split(";")[1].split("filename=")[1]);
          // let blob = new Blob(['\uFEFF' +data])
          // console.log("blob对象",blob);
          const link = document.createElement('a')
          link.download = filename
          link.style.display = 'none'
          link.href = URL.createObjectURL(blob)
          document.body.appendChild(link)
          link.click()
          URL.revokeObjectURL(link.href)
          document.body.removeChild(link)

          this.getStandardInfo();
        });
    } else {
      message.error("下载资源不存在");
    }
  };
  render() {
    let { titleFirst, unit, deft, writeUnit, author } = this.state;
    return (
      <div className={styles.content}>
        <div className={styles.bannerBox}>
          <div className={styles.bannerTitle}>
            <p>标准与规范</p>
            <p>Standards and specifications</p>
          </div>
        </div>
        <div className={styles.detaiHead}>
          <div className={styles.detaiHeadBody}>
            <span
              className={this.state.tabs === 0 ? `${styles.active}` : ""}
              onClick={() => this.handleTabsChange(0)}
            >
              详情
            </span>
            <span
              className={this.state.tabs === 1 ? `${styles.active}` : ""}
              onClick={() => this.handleTabsChange(1)}
            >
              列表
            </span>
          </div>
        </div>
        <div className={styles.detailBody}>
          {this.state.tabs === 0 ? (
            <div className={styles.detailContent}>
              <Card className={styles.detailContentHead}>
                <div className={styles.fl}>
                  <div className={styles.descriptionsIcon}>
                    {
                      this.state.getStandardList.logo ?
                        <img
                          src={this.state.getStandardList.logo}
                          alt=""
                          style={{ width: "100%", height: "100%" }}
                        />
                        :
                        titleFirst
                    }
                  </div>
                </div>
                <p>{this.state.getStandardList.num}——{this.state.getStandardList.tile}</p>
                <div className={styles.clearfix}>
                  <div className={styles.fl}>
                    <span className={styles.littleTitle}>
                      {this.state.getStandardList.subtitle}
                    </span>
                    <span className={styles.clickNum}>
                      点击量：
                      <span className={styles.num}>
                        {this.state.getStandardList.visitNum}
                      </span>
                    </span>
                    <span className={styles.clickNum}>
                      标准状态：
                      <span className={styles.num}>
                        {this.state.getStandardList.behaviourName}
                      </span>
                    </span>
                  </div>
                  <div className={styles.fr}>
                    <Button
                      className={styles.downloadBtn}
                      onClick={() =>
                        this.download(this.state.getStandardList.fileUrl)
                      }
                    >
                      立即下载
                    </Button>
                  </div>
                </div>
              </Card>
              <Card className={styles.detailContentBody}>
                <Descriptions column={2}>
                  <Descriptions.Item label="标题">
                    {this.state.getStandardList.tile}
                  </Descriptions.Item>
                  <Descriptions.Item label="副标题">
                    {this.state.getStandardList.subtitle}
                  </Descriptions.Item>
                  <Descriptions.Item label="标准号">
                    {this.state.getStandardList.num}
                  </Descriptions.Item>
                  <Descriptions.Item label="标准类别">
                    {this.state.getStandardList.typeName}
                  </Descriptions.Item>
                  <Descriptions.Item label="所属学科">
                    {this.state.getStandardList.subjectName}
                  </Descriptions.Item>
                  <Descriptions.Item label="发布日期">
                    {this.state.getStandardList.releaseTime}
                  </Descriptions.Item>
                  <Descriptions.Item label="实施日期">
                    {this.state.getStandardList.effectDate}
                  </Descriptions.Item>
                  <Descriptions.Item label="废止日期">
                    {this.state.getStandardList.endTime}
                  </Descriptions.Item>
                  <Descriptions.Item label="中国标准分类号">
                    {this.state.getStandardList.chinaTypeNum}
                  </Descriptions.Item>
                  <Descriptions.Item label="国际标准分类号">
                    {this.state.getStandardList.nationalTypeNum}
                  </Descriptions.Item>
                  <Descriptions.Item
                    label="归口单位"
                    span={2}
                    className={styles.ulList}
                  >
                    <ul>
                      {unit.split(/[,，、 ]/).map((item, index) => {
                        return <li key={index}>{item}</li>;
                      })}
                    </ul>
                  </Descriptions.Item>
                  <Descriptions.Item label="执行单位" span={2}>
                    {this.state.getStandardList.executeUnit}
                  </Descriptions.Item>
                  <Descriptions.Item
                    label="主管部门"
                    span={2}
                    className={styles.ulList}
                  >
                    <ul>
                      {deft.split(/[,，、 ]/).map((item, index) => {
                        return <li key={index}>{item}</li>;
                      })}
                    </ul>
                  </Descriptions.Item>
                </Descriptions>
              </Card>

              <Card className={styles.detailContentBody}>
                <Descriptions column={1}>
                  <Descriptions.Item label="起草单位" className={styles.ulList}>
                    <ul>
                      {writeUnit.split(/[,，、 ]/).map((item, index) => {
                        return <li key={index}>{item}</li>;
                      })}
                    </ul>
                  </Descriptions.Item>
                </Descriptions>
              </Card>
              <Card className={styles.detailContentBody}>
                <Descriptions column={1}>
                  <Descriptions.Item label="起草人" className={styles.ulList}>
                    <Row gutter={[16, 9]} style={{ width: "100%" }}>
                      {author.split(/[,，、 /]/).map((item, index) => {
                        return (
                          <Col key={index} span={8}>
                            {item}
                          </Col>
                        );
                      })}
                    </Row>
                  </Descriptions.Item>
                </Descriptions>
              </Card>
              <Card className={styles.detailContentBody}>
                <Descriptions column={1}>
                  <Descriptions.Item label="标准简介">
                    {this.state.getStandardList.content}
                  </Descriptions.Item>
                </Descriptions>
              </Card>
              <div style={{ width: "100%", height: "320px", margin: "30px auto 50px" }}>
                <Chart
                  option={this.state.hotWordVos}
                  onChartClick={this.onHotWordVosClick}
                />
              </div>
              <Button
                className={styles.detailContentBtn}
                onClick={() =>
                  this.download(this.state.getStandardList.fileUrl)
                }
              >
                立即下载
              </Button>
            </div>
          ) : (
            <div className={styles.detailTable}>
              <div className={styles.searchBox}>
                <Form layout="inline">
                  <Form.Item label="关键字">
                    <Input
                      placeholder="请输入关键字"
                      value={this.state.value}
                      onChange={e => this.onChange(e)}
                    />
                  </Form.Item>
                  <Form.Item>
                    <Button type="primary" onClick={this.onSearch}>
                      查询
                    </Button>
                    <Button onClick={this.clear}>重置</Button>
                  </Form.Item>
                </Form>
              </div>
              <Table
                dataSource={this.state.StandDetailList}
                columns={this.state.column}
              />
            </div>
          )}
        </div>
      </div>
    );
  }
}

export default StandardDetail;
